<?php
    namespace app\index\controller;
    use think\Db;
    use app\api\validate\Code;
    use think\Exception;
    use yaliSDK\common\BaseRepository;
    use yaliSDK\common\Constrants;
    use yaliSDK\common\Result;
    use yaliSDK\live\LiveService;
    use yaliSDK\netstar\NetstarService;
    use yaliSDK\user\UserService;
    use yaliSDK\utils\Json;
    use yaliSDK\utils\WXHelper;
    use yaliSDK\utils\Http;
    class Live {
        function getConfig() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $id = $params['id']??1;//配置 默认为1
            $is_set=Db::connect(config('database.db_config1'))->name('LiveSet')->where(['is_use'=>1,'id'=>$id])->find(); //获取数据 入口页配置
            $local = [
                'domain' => 'www.live.com',
                'protocal' => 'http',
                'port' => ':80',
                'version' => 'local',
                'wsUrl'=>'wss://video.yalicloud.com:8282',
                'entryPage'=>$is_set['is_page'],   //入口页面（默认是1：直播，2：其他用于审核页面）
                'wxAppid'=>$is_set['wx_appid']
            ];

            $benfor = [
                'domain' => 'video.yalicloud.com',
                'protocal' => 'https',
                'port' => '',
                'version' => 'benfor',
                'wsUrl'=>'wss://video.yalicloud.com:8282',
                'entryPage'=>$is_set['is_page'],
                'wxAppid'=>$is_set['wx_appid']
            ];
            $pro = [
                'domain' => 'gm.yalicloud.com',
                'protocal' => 'https',
                'port' => '',
                'version' => 'pro',
                'wsUrl'=>'wss://gm.yalicloud.com:8282',
                'entryPage'=>$is_set['is_page'], //
                'wxAppid'=>$is_set['wx_appid']
            ];
            $c = $pro;
            return Json::classToArray(new Result([
                'wsUrl'=>$c['wsUrl'],
                'serverUrl' => $c['protocal'].'://'.$c['domain'].$c['port'],
                'roomServiceUrl'=> 'https://room.qcloud.com',
                'version' => $c['version'],
                'entryPage'=>$c['entryPage'],
                'wxAppid'=>$c['wxAppid']
            ]));
        }
        // 获取直播的配置信息
        function getLiveSet() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $id = $params['id']??null;
            $version = $params['version'] ?? 'benfor';// 判断是pro还是local还是benfor
            if (empty($id)) {
                return new Result('id', Constrants::$CUSTOMER_PARAMS_ERROR);
            }
            return Json::classToArray(new Result(LiveService::getLiveRet($version, $id)));
        }
        /**
         * 角色为商家，消费者，网红
         * 用户授权，传入openid，检查用户是否注册，
         * 1.没注册的用户，默认自动注册，角色为消费者；
         * 2.已注册用户，判断是消费者，商家还是网红
         */
        function authorize() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];

            $code = $params['code'] ?? null;
            $appid = $params['appid'] ?? null;
//            $roleType = $params['roleType'] ?? null;// roleType: user: 用户端, anchor: 主播端

            $wxinfo = WXHelper::getWxInfoByCode($code, WXHelper::getWXSetByAppId($appid));// 读取直播的配置项
            // 授权成功
            try {
                if (!empty($wxinfo) && property_exists($wxinfo, 'openid')) {
                    $openid = $wxinfo->openid ?? null;

                    $userService = new NetstarService();
                    $result = $userService->anchorDetail($openid, ['id'=>$openid, 'key' => 'open_id']);// 查询网红信息
                    $user = Result::_getInstanceData($result);
                    // 用户找不到
                    if (empty($user)) {
                        return Json::classToArray(new Result(null, Constrants::$NO_EXIST));
                    }

                    $_res = [];// 返回结果
                    $_res['user'] = $user;
                    $_res['role'] = Constrants::$ROLE_ANCHOR;
                    return Json::classToArray(new Result($_res));

                } else {
                    return Json::classToArray(new Result('无openid', Constrants::$NO_EXIST));
                }

            } catch (Exception $e) {
                return Json::classToArray(new Result($e->getMessage(), \yaliSDK\message\Code::$ERROR));
            }
            // checkUserType
        }

        // 申请网红
        function applySignAnchor() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $openid = $params['openid'] ?? null;
            $name = $params['name'] ?? null;
            $sex = $params['sex'] ?? null;
            $id_front = $params['id_front'] ?? '';
            $id_back = $params['id_back'] ?? '';
            $service = new NetstarService();
            return Json::classToArray($service->applySignAnchor($openid, $name, $sex, $id_front, $id_back));
        }

        // 同意网红
        function agreeSignAnchor() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->agreeSignAnchor($anchorId));
        }

        // 拒绝网红
        function rejectSignAnchor() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->rejectSignAnchor($anchorId));
        }

        // 获取主播列表
        function getAnchors() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $service = new NetstarService();
            return Json::classToArray($service->anchors($params));
        }

        // 获取网红直播列表
        function getAnchorLives() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $service = new NetstarService();
            $result = $this->test($params, function(NetstarService $service, $params){ return $service->anchorLives($params,'keywords');});
           return Json::classToArray($result);

        }

        function test($params, $cb) {
            $service = new NetstarService();
            $result = $cb($service, $params);
            if (!$result instanceof Result) {
                return $result;
            }
            $isProduct = $params['isProduct'] ?? null;// 是否带产品列表
            $isAnchor = $params['isAnchor'] ?? null;// 是否携带主播信息
            $isZan = $params['isZan'] ?? true;// 是否携带主播信息
            $productRows = $params['productRows'] ?? ''; // 产品列表行数
            $_data = $result->getData();
            $list = $_data['list'] ?? null;
            if (!empty($list)) {
                $isMap = $isProduct || $isAnchor || $isZan;// 判断遍历列表 $isVisitorCount
                if ($isMap) {
                    $list = array_map(function ($item) use ($service, $productRows, $isProduct, $isAnchor, $isZan, $params) {
                        if ($isZan) {
                            $d = $service->liveZans(['isCount'=> true, 'live_id'=>$item['id']]);
                            if (!empty($d) &&!is_null($d['total'])) {
                                //$item['total_live_zan'] = $d['total'];
                                $item['total_live_zan'] = $d['total'];
                            }
                        }
                        // 是否携带产品
                        if ($isProduct === true) {
                            $liveId = $item['id'];

                            $p = $service->liveProducts($liveId, $productRows);
                            if ($p instanceof Result && !empty($p->getData())) {
                                $item['products'] = $p->getData();
                            }
                        }

                        if ($isAnchor === true) {
                            $anchorId = $item['anchor_id'];
                            $_params = $params;
                            $_params['id'] = $anchorId;
                            $p = $service->anchorDetail($anchorId, $_params);
                            if ($p instanceof Result && !empty($p->getData())) {
                                $item['anchor'] = $p->getData();

                            }
                        }

                        return $item;
                    }, $list);
                }

                $_data['list'] = $list;

                $result->setData($_data);
            }
            return $result;
        }
        // 获取直播列表
        function getShopLives() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $domain = $params['domain'] ?? null;// 域名
            if (empty($domain)) {
                return Json::classToArray(new Result('domain', Constrants::$CUSTOMER_PARAMS_ERROR));
            }
            $result = $this->test($params, function(NetstarService $service, $params){ return $service->lives($params);});
            return Json::classToArray($result);
        }

        // 创建直播
        function createLive() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $uid = $params['uid'] ?? null;
            $productList = $params['productList'] ?? null;
            $title = $params['title'] ?? null;
            $startTime = $params['startTime'] ?? null;
            $endTime = $params['endTime'] ?? null;
            $anchorId = $params['anchorId'] ?? null;

            $service = new NetstarService();
            return Json::classToArray($service->createLive($uid, $title, $startTime, $endTime, $anchorId, $productList));
        }

        // 编辑直播
        function editLive() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $productList = $params['productList'] ?? null;
            $title = $params['title'] ?? null;
            $startTime = $params['startTime'] ?? null;
            $endTime = $params['endTime'] ?? null;
            $anchorId = $params['anchorId'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->editLive($liveId, $title, $startTime, $endTime, $anchorId, $productList));
        }

        // 结束直播
        function cancelLive() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $service = new NetstarService();
            // 广播
//            $service->broadcastAll(['type' => 'updateLiveStatus', 'liveId' => $liveId, 'status' => Constrants::$LIVE_END]);
            return Json::classToArray($service->cancelLive($liveId));
        }

        // 开始直播
        function startLivePlay() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $roomId = $params['roomId'] ?? null;
            $pushUrlId = $params['pushUrlId'] ?? null;
            $service = new NetstarService();
            // 广播
            return Json::classToArray($service->startLivePlay($liveId, $roomId, $pushUrlId));
        }

        // 结束直播
        function stopLivePlay() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->stopLivePlay($liveId,$params));
        }

        // 当前直播的产品
        function currentLiveProduct() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $productId = $params['productId'] ?? null;
            $service = new NetstarService();
            $result = $service->currentLiveProduct($liveId, $productId);
            if ($result instanceof Result) {
//                try {
//                    $service->broadcastLiveGroup(['type' => 'currentLiveProduct', 'productId' => $productId, 'liveId' => $liveId]);
//                } catch (\Exception $e) {
//                    print_r($e->getMessage());
//                    die;
//                }
            }
            return Json::classToArray($result);
        }

        // 编辑产品价格
        function editProductPrice() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $productId = $params['productId'] ?? null;
            $unitPrice = $params['unitPrice'] ?? null;
            $service = new NetstarService();
            $result = $service->editProductPrice($liveId, $productId, $unitPrice);
//            if ($result instanceof Result && $result->getCodeWXHelper() > 0) {
//                // 广播
//                $service->broadcastLiveGroup(['type' => 'editProductPrice', 'productId' => $productId, 'unitPrice' => $unitPrice]);
//            }
            return Json::classToArray($result);
        }

        // 直播活动产品列表
        function liveProducts() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $rows = $params['rows'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->liveProducts($liveId, $rows));
        }

        // 主播详情
        function anchorDetail() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['id'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->anchorDetail($anchorId, $params));
        }

        // 获取所有活动所属的店铺
        function getLiveShops() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $service = new NetstarService();
            return Json::classToArray($service->getLiveShops($params));
        }
        // 获取主播的活动列表
        function getAnchorLiveShops() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $service = new NetstarService();
            return Json::classToArray($service->getAnchorLiveShops($params));
        }
        // 统计活动参与人数
        function saveLiveVisitor() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $liveId = $params['liveId'] ?? null;
            $openid = $params['openId'] ?? null;
            $uid = $params['uid'] ?? null;
            $domain = $params['domain'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->saveLiveVisitor($liveId, $openid, $uid, $domain));
        }
        // 统计主播点赞
        function saveLiveZan() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $openid = $params['openId'] ?? null;
            $uid = $params['uid'] ?? null;
            $domain = $params['domain'] ?? null;
            $live_id = $params['liveId'] ?? null;
            $service = new NetstarService();
            return Json::classToArray($service->saveLiveZan($anchorId, $openid, $uid, $live_id,$domain));
        }

        function joinLiveGroup() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $clientId = $params['clientId'] ?? null;// workman的client_id，必须存在
            $domain = $params['domain'] ?? null;
            $rpo = new BaseRepository();

            $_a = [];
            if (!empty($domain)) {
                $web_id = $rpo->getWebIdByDomain($domain);
                if (!empty($web_id)) {
                    array_push($_a, 'web_'.$web_id);
                }

            }
            if (!empty($anchorId)) {
                array_push($_a, 'anchor_'.$anchorId);
            }
            $res= Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/joinGroup',
                [
                    'group' => $_a,
                    'clientId' => $clientId,
                ]);
            return json_decode($res);
        }

        function leaveLiveGroup() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $clientId = $params['clientId'] ?? null;// workman的client_id，必须存在
            $domain = $params['domain'] ?? null;
            $rpo = new BaseRepository();

            $_a = [];
            if (!empty($domain)) {
                $web_id = $rpo->getWebIdByDomain($domain);
                if (!empty($web_id)) {
                    array_push($_a, 'web_'.$web_id);
                }

            }
            if (!empty($anchorId)) {
                array_push($_a, 'anchor_'.$anchorId);
            }

            $res = Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/leaveGroup',
                [
                    'group' => $_a,
                    'clientId' => $clientId,
                ]);
            return json_decode($res);
        }

        function addToCart() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $liveId = $params['liveId'] ?? null;
            $username = $params['username'] ?? null;
            $domain = $params['domain'] ?? null;
            $rpo = new BaseRepository();
            $_a = [];
            if (!empty($domain)) {
                $web_id = $rpo->getWebIdByDomain($domain);
                if (!empty($web_id)) {
                    array_push($_a, 'web_'.$web_id);
                }

            }
            if (!empty($anchorId)) {
                array_push($_a, 'anchor_'.$anchorId);
            }
            Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                [
                    'group' => $_a,
                    'msg' => [
                        'type'=>'addToCart',
                        'liveId' => $liveId,
                        'username' => $username,
                    ],
                    'msgId' => request()->time(),
                ],true);
            return Json::classToArray(new Result());
        }
        function addOrder() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $liveId = $params['liveId'] ?? null;
            $username = $params['username'] ?? null;

            $domain = $params['domain'] ?? null;
            $rpo = new BaseRepository();
            $_a = [];
            if (!empty($domain)) {
                $web_id = $rpo->getWebIdByDomain($domain);
                if (!empty($web_id)) {
                    array_push($_a, 'web_'.$web_id);
                }

            }
            if (!empty($anchorId)) {
                array_push($_a, 'anchor_'.$anchorId);
            }

            Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                [
                    'group' => $_a,
                    'msg' => [
                        'type'=>'addOrder',
                        'liveId' => $liveId,
                        'uername' => $username,
                    ],
                    'msgId' => request()->time(),
                ],true);
            return Json::classToArray(new Result());
        }
        function anchorFollow() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];
            $anchorId = $params['anchorId'] ?? null;
            $username = $params['username'] ?? null;
            $liveId = $params['liveId'] ?? null;
            Http::http_request(
                $_SERVER['HTTP_HOST'] . '/api/broadcast/sendGroup',
                [
                    'group' => ['anchor_'.$anchorId],
                    'msg' => [
                        'type'=>'anchorFollow',
                        'liveId' => $liveId,
                        'anchorId' => $anchorId,
                        'username' => $username
                    ],
                    'msgId' => request()->time(),
                ],true);
            return Json::classToArray(new Result());
        }
    }